<?php

class AdminSiteAccountController extends AdminBaseController
{

    public function beforeAction($action)
    {
        parent::beforeAction($action);

        if( !$this->permissionManager->checkRole('work_manager') ) {
            Request::redirect('admin/');
        }

        $this->menus->setFocusByAction('adminSiteAccount/list');
        return true;
    }


    public function actionIndex()
    {
        Request::redirect('list');
    }


    public function actionList( $page=1, $searchKey='' )
    {
        if( Request::isPost() ) {
            $posts = Request::getPostInfo();
            if( $posts['searchKey'] ) {
                $searchKey = $posts['searchKey'];
            }
        }

        $users = new Users();
        $myUsers  = $users->getUsers( $searchKey, $page );
        $rowCount = $users->getCountByUsers( $searchKey );
        $this->pageLimit = new PageLimitManager();
        $this->pageLimit->setBaseUrl( $this->createUrl('') );
        $this->pageLimit->setRowCount( $rowCount );
        $this->pageLimit->setPageShowCount( BaseMapper::DEFAULT_ROW_COUNT );
        $this->pageLimit->setPage( $page );
        $this->pageLimit->setSearchKey( $searchKey );

        $this->render('list',array(
            'users' => $myUsers,
            'searchKey' => $searchKey,
            'page' => $page,
            'deleteAction' => $this->createUrl('adminAccount/delete'),
        ));
    }

    public function actionEdit( $id )
    {

        /* if( 權限錯誤 ) {
            //
        } */
        $id = (int) $id;
        $users = new Users();
        $user = $users->getUser($id);
        if(!$user) {
            Request::redirect('list');
        }
        /*
        if($user 不是我自己) {
            $this->render('error',array('message'=>$msgManager));
        }
        */

        // update 
        if( Request::isPost() ) {
            $posts = Request::getPostInfo();
            $user->setEmail( $posts['email'] );
            $user->setStatus( $posts['status'] );

            $messages = $user->validate();
            $user->filter();
            if( $messages ) {
                SessionManager::setErrorMessages('更新失敗');
                $data['fieldsMessages'] = $messages;
                $data['user'] = $user;
                $this->render('edit', $data );
                return;
            }


            // 取得所有權限, 用來比對要更新的權限
            $userPermissionCategories = new UserPermissionCategories();
            $allPermissions = $userPermissionCategories->getUserPermissionCategories();

            // 更新權限
            $permissions = $posts['permissions'];
            /*
                echo '<pre style="background-color:#def;color:#000;text-align:left;font-size:10px;font-family:dina,GulimChe;">';
                print_r($allPermissions);
                print_r($posts['permissions']);
                echo "</pre>\n";
            */

            $allowSavePermissions = Array();
            if( $permissions ) {
                $allMatch = true; // 權限必須要全部 match, 如果不是就代表有錯誤, 不能讓它儲存
                foreach( $permissions as $permissionKey ) {
                    $isMatch = false;
                    foreach( $allPermissions as $permission ) {
                        if( $permission->getKeyName() == $permissionKey ) {
                            $allowSavePermissions[] = $permission;
                            $isMatch = true;
                            break;
                        }
                    }
                    if( !$isMatch ) {
                        $allMatch = false;
                        break;
                    }
                }

                if( !$allMatch ) {
                    SessionManager::setErrorMessages('權限錯誤, 更新失敗');
                    $data['user'] = $user;
                    $this->render('edit', $data );
                    return;
                }

                // clear permission links
                $userPermissionCategoryLinks = new UserPermissionCategoryLinks();
                $userPermissionCategoryLinks->deleteUserPermissionCategoryLinkByUserId( $user->getId() );

                // add permission links
                foreach( $allowSavePermissions as $allowSavePermission ) {
                    $userPermissionCategoryLink = new UserPermissionCategoryLink();
                    $userPermissionCategoryLink->setUserId( $user->getId() );
                    $userPermissionCategoryLink->setCategoryId( $allowSavePermission->getId() );
                    $userPermissionCategoryLinks->addUserPermissionCategoryLink( $userPermissionCategoryLink );
                }

            }


            $user->setUpdateDate(time());
            $users->updateUser($user);
            SessionManager::setSuccessMessages('更新成功');

/*
            // if set password
            // ...... 
            // $user->setPassword ( $row["password"] );

            // if set email
            // ...... 
            // $user->setEmail ( $row["email"] );
            // $user->setEmailStatus ( User::email_status_nothing );

            // update
            
*/
        }
        // edit
        else {




        }


        $data['user'] = $user;
        $this->render('edit',$data);

    }

    public function actionNew()
    {
        /* if( 權限錯誤 ) {
            //
        } */
        $user = new User();

        // add
        if( Request::isPost() ) {

            $posts = Request::getPostInfo();
            $user = new User();
            $user->setAccount           ( $posts['account']     );
            $user->setPassword          ( $posts["password"]    );
            $user->setEmail             ( $posts["email"]       );
            $user->setStatus            ( $posts["status"]      );
            $user->setAuthType          ( $posts["authType"]    );
            $user->setCreateDate        ( time() );
            $user->setUpdateDate        ( time() );

            $messages = $user->validate();
            // check two password
            if( strlen($posts["password"])<=4 ) {
                $messages['password']['message'] = '密碼必須大於 4 個字元';
            }
            elseif( $posts["password"] != $posts["password2"] ) {
                $messages['password']['message'] = '兩組密碼不正確';
            }
            $user->filter();
            if( $messages ) {
                SessionManager::setErrorMessages('新增失敗');
                $data['fieldsMessages'] = $messages;
                $data['user'] = $user;
                $this->render('new', $data );
                return;
            }
            $users = new Users();
            $users->addUser($user);
            SessionManager::setSuccessMessages('新增成功');


        }

        // new
        $data['user'] = new User();
        $this->render( 'new', $data );

    }


    public function actionDelete( $id=0 )
    {

        /* if( 權限錯誤 ) {
            //
        } */

        // check id or ids
        if( Request::isPost() ) {
            $posts = Request::getPostInfo();
            if( !is_array($posts['chooseItems']) ) {
                Request::redirect('list');
            }
            foreach( $posts['chooseItems'] as $chooseItem ) {
                $ids[] = (int) $chooseItem;
            }
        }
        else {
            if(!$id) {
                Request::redirect('list');
            }
            $ids[] = $id;
        }

        $users = new Users();
        foreach( $ids as $id ) {
            $user = $users->getUser($id);
            if(!$user) {
                $msg =  'error id = '.$id;
                SessionManager::setErrorMessages($msg);
            }
            else {
                $msg =  'success id = '.$id;
                SessionManager::setSuccessMessages($msg);
            }
            
            // delete
            // ..........
            // $result = $users->deleteUser($user);
            
        }

        

        //$data['user'] = $user;
        //$this->render('list',$data);
        $this->actionList();

    }

}
